import { Response } from 'express';
import mongoose, { Types } from 'mongoose';
import { AuthenticatedRequest } from '../types/auth';
import { AuthenticatedRequestHandler } from '../types/express';
import { asyncHandler } from '../middleware/asyncHandler';
import { createError } from '../types/errors';
import EvaluationModel from '../models/evaluationModel';
import { EvaluationStandards } from '../config/evaluationConfig';
import { log } from '../utils/logger';

interface AIEvaluationParams {
  evaluationId: string;
}

interface AdjustEvaluationBody {
  adjustedScore: number;
  feedback: string;
}

interface BatchTriggerBody {
  evaluationIds: string[];
}

// 响应类型定义
interface AIEvaluationResponse {
  score: number;
  confidence: number;
  needsHumanReview: boolean;
  metrics: {
    accuracy: number;
    completion: number;
    creativity: number;
    reasoning: number;
  };
  knowledgePoints: Array<{
    name: string;
    mastery: number;
    suggestions: string[];
  }>;
  strengths: string[];
  weaknesses: string[];
}

interface AIResponse {
  score: number;
  confidence: number;
  feedback: string;
  metrics: {
    accuracy: number;
    completion: number;
    creativity: number;
    reasoning: number;
  };
  knowledgePoints: Array<{
    name: string;
    mastery: number;
    suggestions: string[];
  }>;
  strengths: string[];
  weaknesses: string[];
}

import { VolcanoAI } from '../services/volcanoAI';
const volcanoAI = new VolcanoAI(process.env.VOLCANO_API_KEY!);

// AI评分服务
async function getAIEvaluation(answer: string, questionType: string): Promise<AIResponse> {
  if (!answer?.trim()) {
    throw createError('VALIDATION_ERROR', '答案不能为空');
  }

  if (!questionType?.trim()) {
    throw createError('VALIDATION_ERROR', '题目类型不能为空');
  }

  try {
    const result = await volcanoAI.evaluateAnswer({
      answer,
      type: questionType,
      options: {
        includeKnowledgePoints: true,
        includeStrengthsWeaknesses: true
      }
    });

    return {
      score: result.score,
      confidence: result.confidence,
      feedback: result.feedback,
      metrics: {
        accuracy: result.metrics.accuracy,
        completion: result.metrics.completion,
        creativity: result.metrics.creativity,
        reasoning: result.metrics.reasoning
      },
      knowledgePoints: result.knowledge_points.map(kp => ({
        name: kp.name,
        mastery: kp.mastery,
        suggestions: kp.improvement_suggestions
      })),
      strengths: result.analysis.strengths,
      weaknesses: result.analysis.weaknesses
    };
  } catch (error) {
    log.error('火山引擎AI评分失败:', { error });
    throw createError('SERVICE_UNAVAILABLE', 'AI评分服务暂时不可用');
  }
}

// 触发AI评分
export const triggerAIEvaluation = asyncHandler<AIEvaluationParams>(
  async (req: AuthenticatedRequest, res: Response): Promise<void> => {
    const { evaluationId } = req.params;
    
    if (!evaluationId?.trim()) {
      throw createError('VALIDATION_ERROR', '评估ID不能为空');
    }

    // 开启事务
    const session = await mongoose.startSession();
    session.startTransaction();

    try {
      const evaluation = await EvaluationModel.findById(evaluationId)
        .populate('questionId')
        .session(session);

      if (!evaluation) {
        throw createError('NOT_FOUND', '评价记录不存在');
      }

      if (!evaluation.answers || evaluation.answers.length === 0) {
        throw createError('VALIDATION_ERROR', '答案不存在');
      }

      // 获取AI评分
      const mainAnswer = evaluation.answers[0].answer;
      const aiResult = await getAIEvaluation(
        mainAnswer,
        (evaluation.questionId as any).type
      );

      // 判断是否需要人工复核
      const needsHumanReview = aiResult.confidence < EvaluationStandards.aiScoring.humanReviewThreshold;

      // 更新评价记录
      evaluation.score = needsHumanReview ? undefined : aiResult.score;
      evaluation.feedback = needsHumanReview ? undefined : aiResult.feedback;
      evaluation.status = needsHumanReview ? 'reviewing' : 'completed';
      evaluation.metrics = aiResult.metrics;
      
      await evaluation.save({ session });
      await session.commitTransaction();

      res.json({
        score: aiResult.score,
        confidence: aiResult.confidence,
        needsHumanReview,
        metrics: aiResult.metrics,
        knowledgePoints: aiResult.knowledgePoints,
        strengths: aiResult.strengths,
        weaknesses: aiResult.weaknesses
      });
    } finally {
      session.endSession();
    }
  }
);

// 获取AI评分历史
export const getAIEvaluationHistory = asyncHandler<AIEvaluationParams>(
  async (req: AuthenticatedRequest, res: Response): Promise<void> => {
    const { evaluationId } = req.params;
    
    if (!evaluationId?.trim()) {
      throw createError('VALIDATION_ERROR', '评估ID不能为空');
    }

    const evaluation = await EvaluationModel.findById(evaluationId)
      .select('score metrics history')
      .populate('history.evaluatedBy', 'username');

    if (!evaluation) {
      throw createError('NOT_FOUND', '评价记录不存在');
    }

    res.json({
      score: evaluation.score,
      metrics: evaluation.metrics,
      history: evaluation.history
    });
  }
);

// 人工调整AI评分
export const adjustAIEvaluation = asyncHandler<AIEvaluationParams, unknown, AdjustEvaluationBody>(
  async (req: AuthenticatedRequest, res: Response): Promise<void> => {
    const { evaluationId } = req.params;
    const { adjustedScore, feedback } = req.body;

    // 检查权限
    if (!req.user || !['teacher', 'admin'].includes(req.user.role)) {
      throw createError('FORBIDDEN', '权限不足');
    }

    // 参数验证
    if (!evaluationId?.trim()) {
      throw createError('VALIDATION_ERROR', '评估ID不能为空');
    }

    if (typeof adjustedScore !== 'number' || adjustedScore < 0 || adjustedScore > 100) {
      throw createError('VALIDATION_ERROR', '分数必须在0-100之间');
    }

    if (!feedback?.trim()) {
      throw createError('VALIDATION_ERROR', '评价不能为空');
    }

    // 开启事务
    const session = await mongoose.startSession();
    session.startTransaction();

    try {
      const evaluation = await EvaluationModel.findById(evaluationId)
        .session(session);

      if (!evaluation) {
        throw createError('NOT_FOUND', '评价记录不存在');
      }

      if (!evaluation.history) {
        evaluation.history = [];
      }

      // 记录调整历史
      evaluation.history.push({
        score: adjustedScore,
        feedback,
        evaluatedBy: new Types.ObjectId(req.user._id),
        evaluatedAt: new Date()
      });

      // 更新最终分数
      evaluation.score = adjustedScore;
      evaluation.feedback = feedback;
      evaluation.status = 'completed';

      await evaluation.save({ session });
      await session.commitTransaction();

      res.json({
        message: '评分调整成功',
        score: adjustedScore,
        history: evaluation.history
      });
    } finally {
      session.endSession();
    }
  }
);

// 批量触发AI评分
export const batchTriggerAIEvaluation = asyncHandler<unknown, unknown, BatchTriggerBody>(
  async (req: AuthenticatedRequest, res: Response): Promise<void> => {
    const { evaluationIds } = req.body;

    // 参数验证
    if (!Array.isArray(evaluationIds) || evaluationIds.length === 0) {
      throw createError('VALIDATION_ERROR', '评估ID列表不能为空');
    }

    if (evaluationIds.length > 100) {
      throw createError('VALIDATION_ERROR', '单次批量处理不能超过100条');
    }

    // 开启事务
    const session = await mongoose.startSession();
    session.startTransaction();

    try {
      const results = await Promise.all(
        evaluationIds.map(async (id: string) => {
          try {
            const evaluation = await EvaluationModel.findById(id)
              .populate('questionId')
              .session(session);

            if (!evaluation) {
              return { id, error: '评价记录不存在' };
            }

            if (!evaluation.answers || evaluation.answers.length === 0) {
              return { id, error: '答案不存在' };
            }

            const mainAnswer = evaluation.answers[0].answer;
            const aiResult = await getAIEvaluation(
              mainAnswer,
              (evaluation.questionId as any).type
            );

            const needsHumanReview = aiResult.confidence < EvaluationStandards.aiScoring.humanReviewThreshold;

            evaluation.score = needsHumanReview ? undefined : aiResult.score;
            evaluation.feedback = needsHumanReview ? undefined : aiResult.feedback;
            evaluation.status = needsHumanReview ? 'reviewing' : 'completed';
            evaluation.metrics = aiResult.metrics;

            await evaluation.save({ session });

            return {
              id,
              success: true,
              score: aiResult.score,
              needsHumanReview
            };
          } catch (error) {
            log.error('批量AI评分处理单条记录失败:', { evaluationId: id, error });
            return { id, error: '处理失败' };
          }
        })
      );

      await session.commitTransaction();
      
      res.json({
        message: '批量AI评分处理完成',
        results
      });
    } finally {
      session.endSession();
    }
  }
);
